﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Moonwish.Silverlight.OsAvatar.InternalApp;
using Moonwish.Silverlight.OsAvatar.Utility;
using Moonwish.Silverlight.OsAvatar.Windows;

namespace Moonwish.Silverlight.OsAvatar.Programs
{
    /// <summary>
    /// 普通程序，默认窗口打开。
    /// write by zhlin 2012-02-25
    /// </summary>
    public class ClassicProgram : ProgramWrapper
    {
        private const string WINDOWPREFIX = "window";
        private const string TASKPREFIX = "task";
        /// <summary>
        /// 打开窗口，显示内容。
        /// </summary>
        public override void Show()
        {
            var window = ShowWindow(); 

            if (!string.IsNullOrEmpty(FullPath))
            {
                var pathInfo = FullPath.Split('/');
                var manager = new XapAssembliesManager();
                manager.LoadAssembliesFromXapCompleted += (s, e) =>
                {
                    if (e.Error != null)
                    {
                        window.Content = new TextBlock
                        {
                            Text = e.Error.Message,
                            Margin = new Thickness(20, 20, 0, 0),
                            FontSize = 14,
                            Foreground = new SolidColorBrush(Colors.Red)
                        };
                        return;
                    }
                    var assembly = e.Assemblies.FirstOrDefault(ass => ass.GetType(pathInfo[1]) != null);
                    if (assembly != null)
                    {
                        var instance = assembly.CreateInstance(pathInfo[1]);
                        window.Content = instance;
                    }
                };
                manager.LoadAssembliesFromXap(pathInfo[0]);
            }
            if (Children.Count > 0)
            {
                window.Width = window.MinWidth;
                window.Height = window.MinHeight;
                var explorer = new Explorer();
                explorer.DataContext = this;
                window.Content = explorer;
            }
            else
            {
                window.Height = _windowWrapper.ActualHeight * .8;
                window.Width = _windowWrapper.ActualWidth * .8;
            }
            Canvas.SetLeft(window, (_windowWrapper.ActualWidth - Math.Max(window.Width, window.MinWidth)) * 0.5);
            Canvas.SetTop(window, (_windowWrapper.ActualHeight - Math.Max(window.Height, window.MinHeight)) * 0.5);
        }

        /// <summary>
        /// 
        /// </summary>
        private AvatarWindow ShowWindow()
        {
            var window = _windowWrapper.Children.OfType<AvatarWindow>().FirstOrDefault(obj => obj.Name == WINDOWPREFIX + Id);
            if (window == null)
            {
                window = new AvatarWindow();
                window.Caption = GetDesktopPath(this);
                window.Name = WINDOWPREFIX + Id;
                window.Closed += WindowClosed;
                window.Maximized += WindowMaximized;
                window.Normalized += WindowNormalized;
                window.Minimized += WindowMinimized;
                window.ResizeEnabled = ResizeEnabled;
                _windowWrapper.Children.Add(window);

                var item = new TaskBarItem();
                item.Name = TASKPREFIX + Id;
                item.Icon = Icon16 ?? item.Icon;
                item.Caption = Name;
                //item.ApplyTheme();
                item.Clicked += TaskBarItemClicked;
                _taskWrapper.Children.Add(item);
            }
            window.Visibility = Visibility.Visible;
            window.Focus();
            return window;
        }

        private static void TaskBarItemClicked(object sender, EventArgs e)
        {
            var taskBarItem = (TaskBarItem)sender;
            var window = _windowWrapper.Children.OfType<AvatarWindow>().FirstOrDefault(obj => obj.Name == taskBarItem.Name.Replace(TASKPREFIX, WINDOWPREFIX));
            if (window != null)
            {
                window.Visibility = window.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
                if (window.Visibility == Visibility.Visible)
                {
                    window.Focus();
                }
            }
        }

        private static void WindowClosed(object sender, EventArgs e)
        {

            var window = (AvatarWindow)sender;
            window.Closed -= WindowClosed;
            window.Maximized -= WindowMaximized;
            window.Normalized -= WindowNormalized;
            window.Minimized -= WindowMinimized;
            _windowWrapper.Children.Remove(window);

            var task = _taskWrapper.Children.OfType<TaskBarItem>().FirstOrDefault(obj => obj.Name == window.Name.Replace(WINDOWPREFIX, TASKPREFIX));
            //if (w.Content is InternetExplorer)
            //{
            //    ((InternetExplorer)w.Content).RemoveIFrame();
            //}
            if (task != null)
            {
                _taskWrapper.Children.Remove(task);
            }
        }

        private static void WindowNormalized(object sender, EventArgs e)
        {
            var window = (AvatarWindow)sender;
            window.Width = window.MinWidth;
            window.Height = window.MinHeight;
            Canvas.SetLeft(window, (_windowWrapper.ActualWidth - window.MinWidth) * 0.5);
            Canvas.SetTop(window, (_windowWrapper.ActualHeight - window.MinHeight) * 0.5);
        }

        private static void WindowMaximized(object sender, EventArgs e)
        {
            var window = (AvatarWindow)sender;
            Canvas.SetLeft(window, 0.0);
            Canvas.SetTop(window, 0.0);
            window.Width = _windowWrapper.ActualWidth;
            window.Height = _windowWrapper.ActualHeight;
        }

        private static void WindowMinimized(object sender, EventArgs e)
        {
            var window = (AvatarWindow)sender;

            window.Visibility = Visibility.Collapsed;
        }
    }
}
